﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net.Mail;

public partial class Views_order_confirm : System.Web.UI.UserControl
{
    protected string order_id = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        //if(IsPostBack){

            loadCart();
        //}
    }
    public void loadCart()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("image");
        dt.Columns.Add("product_id");
        dt.Columns.Add("product_name");
        dt.Columns.Add("price");
        dt.Columns.Add("quantity");
        dt.Columns.Add("total");
        DataRow dr;
        for (int i = 0; i < cartBus.carts.listcart.Count; i++)
        {
            product pro = cartBus.carts.listcart[i].Product;
            dr = dt.NewRow();
            dr["image"] = "~//images//" + pro.Image;
            dr["product_id"] = pro.Product_id;
            dr["product_name"] = pro.Product_name;
            dr["price"] = pro.Price;
            dr["quantity"] = cartBus.carts.listcart[i].Quantity;
            dr["total"] = pro.Price * cartBus.carts.listcart[i].Quantity;
            dt.Rows.Add(dr);
            
        }
        confirmCart.DataSource = dt;
        confirmCart.DataBind();        
    }
    public string CheckoutUrl()
    {
        String return_url = "http://demo.nganluong.vn";// Địa chỉ trả về 
        String transaction_info = "Hãy lập trình thông tin của giao dịch của bạn vào đây";//Thông tin giao dịch
        String order_code = order_id;//Mã giỏ hàng 
        String receiver = "ngocnh210@gmail.com";//Tài khoản nhận tiền 
        String price = cartBus.carts.subtotal().ToString();
        NL_Checkout nl = new NL_Checkout();
        String url;
        return url = nl.buildCheckoutUrl(return_url, receiver, transaction_info, order_code, price);        
    }
    protected void click_Back(object sender, EventArgs e)
    {
        Response.Redirect("~//order.aspx?step=1");
    }
    protected void click_Next(object sender, EventArgs e)
    {
        int payment = Convert.ToInt32(Request.QueryString["payment"]);
        if (payment == 2)
        {
            saveOrder();
            Response.Redirect(CheckoutUrl());
        }else if (payment == 1) {
            saveOrder();
            
            Response.Redirect("order.aspx?step=3");
        }
    }
    public bool saveOrder(){
        bool check = false;
        CustomerBus cusBus = new CustomerBus();
        OrderBus orderBus = new OrderBus();
        if (Session["username"] == "" || Session["username"] == null)
        {
            Response.Redirect("default.aspx");
        }
        else
        {
            string email = Convert.ToString(Session["username"]);
            Customer cus = cusBus.getCustomerByEmail(email);
            
            order order = new order(cus.Customer_id, 1, 1, 1, cartBus.carts.subtotal());
            if(orderBus.addOrder(order)){
                int order_id = orderBus.getOrderID(cus.Customer_id);
                this.order_id = order_id.ToString();
                if (order_id != 0)
                {
                    saveOrderProduct(order_id);
                    sendMailCustomer(order_id);
                    check = true;
                }
                else
                {
                    check = false;
                }
            
            }else{
                check = false;
            }            
        }
        return check;
    }
    public void saveOrderProduct(int order_id)
    {
        OrderBus orderBus = new OrderBus();
        for (int i = 0; i < cartBus.carts.listcart.Count; i++)
        {
            product pro = cartBus.carts.listcart[i].Product;
            order_product order_product=new order_product(order_id,pro.Product_id,pro.Product_name,pro.Price,cartBus.carts.listcart[i].Quantity);
            orderBus.addOrderProduct(order_product);
            orderBus.UpdateProductOrder(pro.Product_id);

        }
    }
    public void sendMailCustomer(int order_id){
        OrderBus orderBus = new OrderBus();
        string status = orderBus.getOrderStatusName(order_id);
        try
        {
            CustomerBus cusBus  = new CustomerBus();
            Customer cus = new Customer();
            SendMail send = new SendMail();
            //cus = cusBus.getCustomerByEmail(Session["username"]);
        
            string to = Session["username"].ToString();
            string from = "teamcodeblock@gmail.com";
            string subject = subjectComment.Text;
            string body = @"
            <htm>l
                <body><div>Ghi chú:</div><div>" + comment.Text + @"</div>
                <div>Hàng đã đặt:</div>
                <Table border=1 style='width=800px;'>
                <tr><td>Tên Mặt Hàng</td>
                <td>Giá</td>
                <td>Số Lượng</td>
                <td>Tổng</td></tr>" + getCart()+
                @"</table><div style='font-weight:bold;corlor:red;font-size:1.2em'>Tình Trạng: " + status + @"</body>
            </html>";
            if (send.Send_Mail(to, subject, body, true) != 0)
            {
                Response.Redirect("~//order.aspx?step=3");
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "Test.com", "<script>alert('Unsuccesfull')</script>", false);
            }
        }catch (SmtpException ex)
        {
            Response.Write(ex.Message);
            ScriptManager.RegisterStartupScript(this, typeof(Page), "Test", "<script>alert('Your email not exist in our system, or authenticated by proxy of server')</script>", false);
        }     
    }
    public string getCart(){
        int payment = Convert.ToInt32(Request.QueryString["payment"]);
        string result=@"<tr>";
        for (int i = 0; i < cartBus.carts.listcart.Count; i++)
        {
            product pro = cartBus.carts.listcart[i].Product;
                result = result + @"<td>" + pro.Product_name + @"</td>";
                result=result+@"<td>"+pro.Price+@"</td>";
                result = result + @"<td>" + pro.Product_quantity + @"</td>";
                result = result + @"<td>" + pro.Price * pro.Product_quantity + @"</td></tr>";
                
         }
        if(payment==1){
            result = result + @"<tr><td>Phuong thuc thanh toan truc tiep</td></tr>";   
        }else{
            result = result + @"<tr><td>Phuong thuc thanh toan qua ngan luong</td></tr>";   
        }
        
        result = result + @"<tr><td'>Thanh Toán: " + cartBus.carts.subtotal() + @"</td></tr>";        
        return result;
    }

    
}